﻿namespace UITest.Selenium.SeleniumControls.HtmlControls
{
    using OpenQA.Selenium;
    using OpenQA.Selenium.Support.UI;

    using UITest.Selenium.SeleniumContext;

    /// <summary>
    ///     The selenium ajax edit.
    /// </summary>
    public class SeleniumAjaxEdit : SeleniumEdit
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SeleniumAjaxEdit"/> class.
        /// </summary>
        /// <param name="seleniumContext">
        /// The selenium context.
        /// </param>
        /// <param name="findBy">
        /// The find by.
        /// </param>
        public SeleniumAjaxEdit(SeleniumContext seleniumContext, By findBy)
            : base(seleniumContext, findBy)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SeleniumAjaxEdit"/> class.
        /// </summary>
        /// <param name="seleniumContext">
        /// The selenium context.
        /// </param>
        /// <param name="webElement">
        /// The web element.
        /// </param>
        public SeleniumAjaxEdit(SeleniumContext seleniumContext, IWebElement webElement)
            : base(seleniumContext, webElement)
        {
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        /// The select by text.
        /// </summary>
        /// <param name="text">
        /// The text.
        /// </param>
        public void SelectByText(string text)
        {
            this.WaitForControlReady();
            this.WriteTestOutput("Select " + text + "on");
            this.WaitUntil(x => this.TryToSelectByText(text), string.Format("Value '{0}' hasn't been selected", text));
        }

        #endregion

        #region Methods

        private bool TryToSelectByText(string text)
        {
            try
            {
                new SelectElement(this.GetWebElement()).SelectByText(text);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion
    }
}